package com.xjt.sentinel.excption;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: xu
 * @Description: TODO
 * @Date: 2021/11/14 22:02
 */
//sentinel统一异常处理
@Component
public class SentinelBloackException implements BlockExceptionHandler
{
	Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception
	{
		logger.error("global service appear down level or exception"+e.getRule());
		String msg;
		if (e instanceof FlowException)
		{
			msg = "present service appear flow impose";
		}else if(e instanceof DegradeException)
		{
			msg = "present service appear fusing";
		}else {
			msg = "service appear exception";
		}
		httpServletResponse.setCharacterEncoding("utf8");
		PrintWriter writer = httpServletResponse.getWriter();
		writer.println(msg);
		writer.flush();
		writer.close();
	}
}
